//
//  ScanViewController.swift
//  CheckmeRing
//
//  Created by 董鹏 on 2022/2/27.
//

import UIKit

class ScanViewController: RViewController {

    var previewView = QiCodePreviewView.init()
    var codeManager = QiCodeManager.init()
    
    typealias backData = (_ result:ScanObject) ->()
    var backData:backData?
    
    override func viewDidLoad() {
        super.viewDidLoad()

//        let photoItem = UIBarButtonItem.init(title: "相册", style: .done, target: self, action: #selector(photo))
//        photoItem.tintColor = hexColor("333333")
//        self.navigationItem.rightBarButtonItem = photoItem
        
        self.previewView = QiCodePreviewView.init(frame: self.view.bounds)
        self.previewView.autoresizingMask = .flexibleHeight
        self.view.addSubview(self.previewView)
        
        self.codeManager = QiCodeManager.init(previewView: self.previewView, completion: { [weak self] in
            self?.startScanning()
        })
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.startScanning()
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        self.codeManager.stopScanning()
    }
    
    func startScanning() {
        self.codeManager.startScanning(callback: { [weak self] result in
            self?.parsingAndBack(result: result)
        }, autoStop: true)
    }
    
    @objc func photo() {
        self.codeManager.presentPhotoLibrary(withRooter: self) { [weak self] result in
            self?.parsingAndBack(result: result)
        }
    }
    
    func parsingAndBack(result: String) {
        let scan1 = ScanObjectOC.mj_object(withKeyValues: result)
        let scanSwift = ScanObject.init()
        if let scan = scan1, let back = self.backData {
            scanSwift.apiurl = scan.apiurl
            scanSwift.userid = scan.userid
            scanSwift.password = scan.password
            back(scanSwift)
            self.navigationController?.popViewController(animated: false)
        }
    }
    
}
